package com.forum.framework.common.util.colletion;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.ArrayUtil;

import java.util.Collection;
import java.util.function.Consumer;
import java.util.function.Function;

import static com.forum.framework.common.util.colletion.CollectionUtils.convertList;

/**
 * Array 工具类
 *
 * @author zihan.ouyang
 */
public class ArrayUtils {
    public static <T> Consumer<T>[] append(Consumer<T> array, Consumer<T>... consumers) {
        if (array == null) {
            return consumers;
        }
        Consumer<T>[] result = ArrayUtil.newArray(Consumer.class, 1 + consumers.length);
        result[0] = array;
        System.arraycopy(consumers, 0, result, 1, consumers.length);
        return result;
    }

    public static <T, V> V[] toArray(Collection<T> from, Function<T, V> mapper) {
        return toArray(convertList(from, mapper));
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] toArray(Collection<T> from) {
        if (CollectionUtil.isEmpty(from)) {
            return (T[]) new Object[0];
        }
        return ArrayUtil.toArray(from, (Class<T>) IterUtil.getElementType(from.iterator()));
    }

    public static <T> T get(T[] array, int index) {
        if (null == array || index >= array.length) {
            return null;
        }
        return array[index];
    }
}
